#!/usr/bin  python
# _*_ coding:utf-8 _*_
"""
----------------------------------
    File Name: category
    Description:
        Author: lhw
        Date: 2020/6/2
-----------------------------------
"""

from datetime import datetime

from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView

from Admin.models import AdminUser
from Admin.models import Tag
from Common.logger import app_log
from Common.open_branch import open_branch
from Common.response import resp
from Common.span_tree import span_tree
from EducationContent import models
from EducationContent.serializers.category import CategoryModelSerializer
from extensions.auth import JwtAuthorizationAuthentication


class CategoryView(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def get(self, request, *args, **kwargs):
        try:
            hospital_id = request.GET.get("hospital_id", "")
            user_email = request.user["data"]["email"]
            language = request.GET.get("language", "")
            if not hospital_id or not language:
                return resp(4002, {})
            hospital = AdminUser.objects.filter(email=user_email).values("hospital").first().get("hospital", "")
            if hospital != "ALL":
                allow_hospital_id = models.Hospital.objects.filter(hospital_name=hospital).values("id").first().get(
                    "id", "")
                if str(allow_hospital_id) != hospital_id:
                    return resp(1002, {})
            language = 'EN'
            if language not in ['EN', 'SP']: return resp(4010)
            all_data = models.EducationCategory.objects.filter(hospital_id=hospital_id).all()
            data_list = []
            for single_data in all_data:
                if not models.EducationCategory.objects.filter(cid=single_data.parent_id).first() and \
                        single_data.parent_id != 'root':
                    continue
                single_data_dict = {}
                single_data_dict["id"] = single_data.id
                single_data_dict["cid"] = single_data.cid
                single_data_dict["parent_id"] = single_data.parent_id
                single_data_dict["title"] = single_data.title if language == 'EN' else single_data.title_SP
                single_data_dict["order_id"] = single_data.order_id
                single_data_dict["level"] = single_data.level
                single_data_dict["type"] = 0
                # 注意点 这里筛选的时候要加hospital_id的筛选
                content_data = models.EducationFeeds.objects.filter(category_id=single_data.cid,
                                                                    hospital_id=hospital_id,
                                                                    is_delete=False
                                                                    ).all()
                if content_data.exists():
                    content_list = []
                    for single_content in content_data:
                        content_dict = {}
                        related_content = []
                        data = single_content.educationFeeds_details_to_json()
                        content_dict["id"] = data["id"]
                        content_dict['type'] = 1
                        # content_dict["source"] = data["source"]
                        source = models.Source.objects.filter(id=int(single_content.source)).first()
                        content_dict["source"] = source.source_to_json() if source else {}
                        content_dict["category_id"] = data["category_id"]
                        content_dict["hospital_id"] = data["hospital_id"]
                        tags_ret = ""
                        tags = []
                        if data['tags']:
                            tags = data["tags"].split(',')
                        if tags:
                            for it in tags:
                                if it:
                                    record = Tag.objects.filter(id=str(it)).first()
                                    if record:
                                        if tags_ret == "":
                                            tags_ret = record.tag_title
                                        else:
                                            tags_ret = tags_ret + ',{}'.format(record.tag_title)

                        content_dict["tags"] = tags_ret
                        # content_dict["tags"] = data['tags']

                        content_dict["related_content"] = related_content
                        if language == 'EN':
                            content_dict["title"] = single_content.title
                            content_dict[
                                "title_media_type"] = single_content.title_media_type if single_content.title_media_url else ""
                        if language == 'SP':
                            content_dict["title"] = single_content.title_SP
                            content_dict[
                                "title_media_type"] = single_content.title_media_type if single_content.title_media_url_SP else ""
                        content_list.append(content_dict)
                    single_data_dict['content_list'] = content_list
                else:
                    single_data_dict['content_list'] = []
                data_list.append(single_data_dict)
            # span tree
            data = span_tree(data_list)

            # real data
            real_data = {}
            real_data["tree_data"] = data
            root_content_list = []
            # append root_content
            root_content_data = models.EducationFeeds.objects.filter(category_id="root",
                                                                     hospital_id=hospital_id,
                                                                     ).all()
            if root_content_data.exists():
                for single_content in root_content_data:
                    root_content_dict = {}
                    root_related_content = []
                    root_data = single_content.educationFeeds_details_to_json()
                    root_content_dict["id"] = root_data["id"]
                    root_content_dict['type'] = 1
                    # root_content_dict["source"] = root_data["source"]
                    source = models.Source.objects.filter(id=int(single_content.source)).first()
                    root_content_dict["source"] = source.source_to_json() if source else {}

                    root_content_dict["category_id"] = root_data["category_id"]
                    root_content_dict["hospital_id"] = root_data["hospital_id"]
                    root_content_dict["tags"] = root_data["tags"]
                    root_content_dict["related_content"] = root_related_content
                    if language == 'EN':
                        root_content_dict["title"] = single_content.title
                        root_content_dict[
                            "title_media_type"] = single_content.title_media_type if single_content.title_media_url else ""
                    if language == 'SP':
                        root_content_dict["title"] = single_content.title_SP
                        root_content_dict[
                            "title_media_type"] = single_content.title_media_type if single_content.title_media_url_SP else ""

                    root_content_list.append(root_content_dict)
            # data.extend([{"content_list": root_content_list}])
            real_data["content_list"] = root_content_list
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': real_data
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, str(e))

    def post(self, request, *args, **kwargs):
        try:
            date = datetime.utcnow()
            app_log.info("/api/admin/education_content/category --> post")
            request_data = request.data
            request_data['created_at'] = date
            request_data['updated_at'] = date
            # title = request_data["title"]
            # hospital_id = request_data["hospital"]
            # title_data = models.EducationCategory.objects.filter(title=title, hospital_id=hospital_id)
            # if title_data.exists():
            #     return resp(4003, {})
            category_ser = CategoryModelSerializer(data=request_data)
            category_ser.is_valid(raise_exception=True)
            category_obj = category_ser.save()
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': CategoryModelSerializer(category_obj).data
            })
        except ValidationError as e:
            app_log.error(e)
            return resp(4006, {})
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def patch(self, request, *args, **kwargs):
        try:
            date = datetime.utcnow()
            cid = request.data.get("cid", "")
            hospital_id = request.data.get("hospital_id", "")
            title = request.data.get("title", "")
            language = request.data.get("language", )
            if title == "":
                return resp(4004, {})
            # is_exist = models.EducationCategory.objects.filter(title=title, hospital_id=hospital_id)
            # if is_exist.exists():
            #     return resp(4003, {})
            if language == "EN":
                models.EducationCategory.objects.filter(cid=cid, hospital_id=hospital_id).update(title=title, updated_at=date)
            elif language == "SP":
                models.EducationCategory.objects.filter(cid=cid, hospital_id=hospital_id).update(title_SP=title, updated_at=date)

            return Response({
                'error_code': 0,
                'message': "Success"
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def delete(self, request, *args, **kwargs):
        try:
            cid = request.GET.get("cid", "")
            hospital_id = request.GET.get("hospital_id", "")
            arm_id = []
            if cid:
                arm_id.append(cid)
                data_queryset = models.EducationCategory.objects.filter(hospital_id=hospital_id).all()
                data_list = []
                for single_data in data_queryset:
                    single_data_dict = {}
                    single_data_dict["cid"] = single_data.cid
                    single_data_dict["parent_id"] = single_data.parent_id
                    single_data_dict["title"] = single_data.title
                    single_data_dict["order_id"] = single_data.order_id
                    single_data_dict["level"] = single_data.level
                    data_list.append(single_data_dict)
                data = open_branch(data_list, arm_id)
                models.EducationCategory.objects.filter(cid=cid, hospital_id=hospital_id).delete()
                models.EducationFeeds.objects.filter(category_id=cid, hospital_id=hospital_id).delete()
                if data:
                    for single_data in data:
                        models.EducationCategory.objects.filter(cid=single_data['cid'],
                                                                hospital_id=hospital_id).delete()
                        models.EducationFeeds.objects.filter(category_id=single_data['cid'],
                                                             hospital_id=hospital_id).delete()
                return Response({
                    'error_code': 0,
                    'message': "Success"
                })
            return resp(4005, {})

        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)


class ModifyOrderCategory(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def post(self, request, *args, **kwargs):
        try:
            hospital_id = request.data.get("hospital_id", "")
            cid_list = request.data.get("cid_list", "")
            # check put params whether correct
            for i, v in enumerate(cid_list):
                i += 1
                models.EducationCategory.objects.filter(cid=v, hospital_id=hospital_id).update(order_id=i)
            return Response({
                'error_code': 0,
                'message': "Success"
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)
